import http from '@/utils/request'
export default {
  namespaced: true,
  state: {
    items: []
  },
  mutations: {
    addGoods (state, payload) {
      // payload = {id,skuId,attrsText,picture,name,price,nowPrice,count,selected,stock}
      // 判断是否有相同规格
      const sameIndex = state.items.findIndex(item => item.skuId === payload.skuId)
      if (sameIndex > -1) {
        // 相同规格
        state.items[sameIndex].count += payload.count
        state.items[sameIndex].price = payload.price
        state.items[sameIndex].nowPrice = payload.nowPrice
      } else {
        // 不同规格
        payload.selected = false
        state.items.unshift(payload)
      }
    },
    delGoods (state, payload) {
      // payload = {skuId}
      const index = state.items.findIndex(item => item.skuId === payload.skuId)
      state.items.splice(index, 1)
    },
    updateGoods (state, payload) {
      const item = state.items.find(item => item.skuId === payload.skuId)
      for (const key in payload) {
        item[key] = payload[key]
      }
    },
    batchDelGoods (state, payload) {
      // payload = {skuIds:[]}
      payload.skuIds.forEach(skuId => {
        const index = state.items.findIndex(item => item.skuId === skuId)
        state.items.splice(index, 1)
      })
    },
    setCart (state, payload) {
      state.items = payload
    }
  },
  actions: {
    // 加入购物车商品
    async addCart (ctx, payload) {
      if (ctx.rootState.user.token) {
        await http.post('member/cart', { skuId: payload.skuId, count: payload.count })
        ctx.commit('addGoods', payload)
      } else {
        ctx.commit('addGoods', payload)
      }
    },
    // 删除购物车商品
    async delCart (ctx, payload) {
      if (ctx.rootState.user.token) {
        let ids = []
        if (payload instanceof Array) {
          ids = payload.map(item => item.skuId)
        } else {
          ids = [payload.skuId]
        }
        await http({
          url: 'member/cart',
          method: 'delete',
          data: { ids }
        })
        ids.forEach(id => {
          ctx.commit('delGoods', { skuId: id })
        })
      } else {
        if (payload instanceof Array) {
          payload.forEach(item => {
            ctx.commit('delGoods', item)
          })
        } else {
          ctx.commit('delGoods', payload)
        }
      }
    },
    // 更新购物车商品
    async updateCart (ctx, payload) {
      if (ctx.rootState.user.token) {
        await http.put('member/cart/' + payload.skuId, payload)
        ctx.commit('updateGoods', payload)
      } else {
        ctx.commit('updateGoods', payload)
      }
    },
    // 初始化购物车数据
    async getCart (ctx) {
      if (ctx.rootState.user.token) {
        const { data } = await http.get('member/cart')
        ctx.commit('setCart', data.result)
      } else {
        const promiseArr = ctx.state.items.map(item => http.get('goods/stock/' + item.skuId))
        const newCart = []
        const resList = await Promise.all(promiseArr)
        resList.forEach((res, i) => {
          newCart[i] = { ...ctx.state.items[i], ...res.data.result }
        })
        ctx.commit('setCart', newCart)
      }
    },
    // 合并购物车的数据
    async mergeCart (ctx) {
      const promiseArr = ctx.state.items.map(item => {
        return http.post('member/cart', { skuId: item.skuId, count: item.count })
      })
      await Promise.all(promiseArr)
      await ctx.dispatch('getCart')
    }
  },
  getters: {
    totalCount: (state) => state.items.reduce((p, n) => p + n.count, 0),
    totalAmount: (state) => state.items.reduce((p, n) => p + n.nowPrice * 100 * n.count, 0) / 100,
    unValidCartItems: (state) => state.items.filter(item => item.stock === 0),
    validCartItems: (state) => state.items.filter(item => item.stock > 0),
    selectedCartItems: (state) => state.items.filter(item => item.selected),
    selectedTotalCount: (state, getters) => getters.selectedCartItems.reduce((p, n) => p + n.count, 0),
    selectedTotalAmount: (state, getters) => getters.selectedCartItems.reduce((p, n) => p + n.nowPrice * 100 * n.count, 0) / 100
  }
}
